import { defineStore } from 'pinia'
import { ref } from 'vue'
import request from '@/utils/request'

// 定义用户类型
interface User {
  tid: number
  user_code: string
  emp_code: string
  user_name: string
  mobile: string
  gender: string
  in_use: number
  insert_time?: string
  update_time?: string
  dept_code?: string
  admin?: number
  org_code?: string
}

// 模拟用户数据
const mockUsers: User[] = [
  {
    tid: 1,
    user_code: 'ADMIN001',
    emp_code: 'EMP001',
    user_name: '管理员',
    mobile: '13800138000',
    gender: '男',
    in_use: 1,
    insert_time: '2023-01-15T08:00:00Z',
    update_time: '2023-10-10T14:20:00Z',
    dept_code: 'DEPT001',
    admin: 1,
    org_code: 'ORG001'
  },
  {
    tid: 2,
    user_code: 'USER001',
    emp_code: 'EMP002',
    user_name: '张三',
    mobile: '13800138001',
    gender: '男',
    in_use: 1,
    insert_time: '2023-02-20T09:15:00Z',
    update_time: '2023-11-05T11:30:00Z',
    dept_code: 'DEPT002',
    admin: 0,
    org_code: 'ORG001'
  },
  {
    tid: 3,
    user_code: 'USER002',
    emp_code: 'EMP003',
    user_name: '李四',
    mobile: '13800138002',
    gender: '女',
    in_use: 1,
    insert_time: '2023-03-05T10:40:00Z',
    update_time: '2023-11-15T15:10:00Z',
    dept_code: 'DEPT003',
    admin: 0,
    org_code: 'ORG001'
  },
  {
    tid: 4,
    user_code: 'USER003',
    emp_code: 'EMP004',
    user_name: '王五',
    mobile: '13800138003',
    gender: '男',
    in_use: 0,
    insert_time: '2023-04-10T13:25:00Z',
    update_time: '2023-11-18T10:50:00Z',
    dept_code: 'DEPT001',
    admin: 0,
    org_code: 'ORG001'
  },
  {
    tid: 5,
    user_code: 'USER004',
    emp_code: 'EMP005',
    user_name: '赵六',
    mobile: '13800138004',
    gender: '女',
    in_use: 1,
    insert_time: '2023-05-15T11:10:00Z',
    update_time: '2023-11-16T16:20:00Z',
    dept_code: 'DEPT002',
    admin: 0,
    org_code: 'ORG001'
  }
]

// 定义 SysUserStore
export const useSysUserStore = defineStore('sysUser', () => {
  // 用户列表，初始化时使用模拟数据
  const userList = ref<User[]>([...mockUsers])

  // 当前编辑的用户
  const currentUser = ref<User | null>(null)

  // 是否正在编辑
  const isEditing = ref(false)

  // 获取用户列表
  const fetchUserList = async () => {
    try {
      const response = await request.get('/api/users')
      if (response && Array.isArray(response.data)) {
        userList.value = response.data
      } else {
        console.warn('获取的用户列表数据格式不正确，使用模拟数据')
        userList.value = [...mockUsers]
      }
    } catch (error) {
      console.error('获取用户列表失败:', error)
      // 发生错误时使用模拟数据
      userList.value = [...mockUsers]
    }
  }

  // 新增用户
  const addUser = async (user: Omit<User, 'tid'>) => {
    try {
      const response = await request.post('/api/users', user)
      if (response && response.data) {
        userList.value.push(response.data)
      } else {
        console.warn('新增用户返回数据格式不正确，使用模拟数据')
        // 模拟添加成功
        const newUser: User = {
          ...user,
          tid: Date.now(), // 使用时间戳作为临时ID
          insert_time: new Date().toISOString(),
          update_time: new Date().toISOString()
        }
        userList.value.push(newUser)
      }
    } catch (error) {
      console.error('新增用户失败:', error)
      // 发生错误时使用模拟数据
      const newUser: User = {
        ...user,
        tid: Date.now(), // 使用时间戳作为临时ID
        insert_time: new Date().toISOString(),
        update_time: new Date().toISOString()
      }
      userList.value.push(newUser)
    }
  }

  // 编辑用户
  const updateUser = async (tid: number, user: Partial<User>) => {
    try {
      const response = await request.put(`/api/users/${tid}`, user)
      if (response && response.data) {
        const index = userList.value.findIndex((u) => u.tid === tid)
        if (index !== -1) {
          userList.value[index] = { ...userList.value[index], ...response.data }
        }
      } else {
        console.warn('编辑用户返回数据格式不正确，使用模拟数据')
        // 模拟编辑成功
        const index = userList.value.findIndex((u) => u.tid === tid)
        if (index !== -1) {
          userList.value[index] = {
            ...userList.value[index],
            ...user,
            update_time: new Date().toISOString()
          }
        }
      }
    } catch (error) {
      console.error('编辑用户失败:', error)
      // 发生错误时使用模拟数据
      const index = userList.value.findIndex((u) => u.tid === tid)
      if (index !== -1) {
        userList.value[index] = {
          ...userList.value[index],
          ...user,
          update_time: new Date().toISOString()
        }
      }
    }
  }

  // 删除用户
  const deleteUser = async (tid: number) => {
    try {
      await request.delete(`/api/users/${tid}`)
      userList.value = userList.value.filter((u) => u.tid !== tid)
    } catch (error) {
      console.error('删除用户失败:', error)
      // 发生错误时使用模拟数据
      userList.value = userList.value.filter((u) => u.tid !== tid)
    }
  }

  // 设置当前编辑的用户
  const setCurrentUser = (user: User | null) => {
    currentUser.value = user
    isEditing.value = !!user
  }

  return {
    userList,
    currentUser,
    isEditing,
    fetchUserList,
    addUser,
    updateUser,
    deleteUser,
    setCurrentUser,
  }
})